package cn.slipi.admin.controller;

import cn.slipi.admin.biz.ConsumerBiz;
import cn.slipi.admin.biz.vo.consumer.CsmProjectVo;
import cn.slipi.admin.common.annotation.Permission;
import cn.slipi.admin.common.dto.PageDTO;
import cn.slipi.admin.common.exception.base.BizException;
import cn.slipi.admin.common.response.JsonResponse;
import cn.slipi.admin.common.utils.WordUtil;
import cn.slipi.admin.constants.AdminConstants;
import cn.slipi.admin.constants.permission.PermissionConstants;
import cn.slipi.admin.controller.form.consumer.GrantForm;
import cn.slipi.admin.controller.form.consumer.ListForm;
import cn.slipi.admin.controller.form.consumer.SaveForm;
import cn.slipi.admin.service.dto.out.doc.WriteDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 生产者
 */
@Validated
@Controller
@ResponseBody
@RequestMapping(AdminConstants.CAR_API_PREFIX + "/consumer")
public class ConsumerController {


    @Autowired
    private ConsumerBiz consumerBiz;

    @PostMapping("/list")
    @Permission(value = {PermissionConstants.CONSUMER_LIST})
    public JsonResponse<PageDTO<CsmProjectVo>> getList(@Valid @RequestBody ListForm listForm) {
        JsonResponse<PageDTO<CsmProjectVo>> responseVo = new JsonResponse<>();
        PageDTO<CsmProjectVo> result = this.consumerBiz.getList(listForm);
        responseVo.setData(result);
        return responseVo;
    }

    @PostMapping("/add")
    @Permission(value = {PermissionConstants.CONSUMER_ADD})
    public JsonResponse<Integer> add(@Valid @RequestBody SaveForm saveForm) {
        JsonResponse<Integer> responseVo = new JsonResponse<>();
        Integer result = this.consumerBiz.add(saveForm);
        responseVo.setData(result);
        return responseVo;
    }

    @PostMapping("/grant")
    @Permission(value = {PermissionConstants.CONSUMER_GRANT})
    public JsonResponse<Boolean> grant(@Valid @RequestBody GrantForm grantForm) {
        JsonResponse<Boolean> responseVo = new JsonResponse<>();
        Boolean result = this.consumerBiz.grant(grantForm);
        responseVo.setData(result);
        return responseVo;
    }

    @GetMapping("/un/grant/{grantId}")
    @Permission(value = {PermissionConstants.CONSUMER_UN_GRANT})
    public JsonResponse<Boolean> unGrant(@PathVariable("grantId") Integer grantId) {
        JsonResponse<Boolean> responseVo = new JsonResponse<>();
        Boolean result = this.consumerBiz.unGrant(grantId);
        responseVo.setData(result);
        return responseVo;
    }

    @GetMapping("/grant/publish/{grantId}")
    @Permission(value = {PermissionConstants.CONSUMER_GRANT_PUBLISH})
    public JsonResponse<Boolean> grantPublish(@PathVariable("grantId") Integer grantId) {
        JsonResponse<Boolean> responseVo = new JsonResponse<>();
        Boolean result = this.consumerBiz.grantPublish(grantId);
        responseVo.setData(result);
        return responseVo;
    }

    @PutMapping("/update/{id}")
    @Permission(value = {PermissionConstants.CONSUMER_UPDATE})
    public JsonResponse<Boolean> update(@PathVariable("id") Integer id, @Valid @RequestBody SaveForm saveForm) {
        JsonResponse<Boolean> responseVo = new JsonResponse<>();
        Boolean result = this.consumerBiz.update(id, saveForm);
        responseVo.setData(result);
        return responseVo;
    }

    @GetMapping("/grant/doc/{id}")
    @Permission(value = {PermissionConstants.CONSUMER_GRANT_DOC})
    public void grantDoc(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) throws UnsupportedEncodingException {
        String userAgent = request.getHeader("User-Agent");
        WriteDTO writeDTO = this.consumerBiz.write(id);
        String fileName = writeDTO.getFileName();
        // 针对IE或者以IE为内核的浏览器：
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.setContentType("application/msword");
        response.setHeader("Content-Disposition", String.format("attachment;filename=%s", fileName));
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        try {
            File file = null;
            FileInputStream fis = null;
            OutputStream sos = response.getOutputStream();
            try {
                String destFile = "D:\\dev\\网关设计" + File.separator + writeDTO.getFileName();
                WordUtil.createWord(writeDTO.getData(), "templetes/api.ftl", destFile);
                int nLen = 0;
                byte[] buff = new byte[512];
                file = new File(destFile);
                fis = new FileInputStream(file);
                sos.flush();
                while ((nLen = fis.read(buff)) > 0) {
                    sos.write(buff, 0, nLen);
                }
                sos.flush();
                sos.close();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                } catch (Exception ignored) {
                }
                try {
                    if (sos != null) {
                        sos.close();
                    }
                } catch (Exception ignored) {
                }
                file = null;
            }
        } catch (IOException e) {
            throw new BizException(10000, "doc.generator.error");
        }

    }

}
